/**
 * 
 */
package com.bskyb.rss.service;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.bskyb.rss.FeedItem;
import com.bskyb.rss.R;
import com.bskyb.rss.RssFeed;
import com.bskyb.rss.configure.RssFeedWidgetConfiguration;
import com.bskyb.rss.parser.RssFeedHandler;
import com.bskyb.rss.widget.SkyNewsReaderAppWidget;

/**
 * @author ShivakP
 * 
 */
public class RssReaderService extends Service {
	private static final String TAG = "RssReaderService";
	private static String CURRENT_FEED = "CURRENT_FEED";
	private static String SITE_SKY_SPORTS = "SITE_SKYSPORTS";
	private static String SITE_SKY_NEWS = "SITE_SKYNEWS";

	@Override
	public void onStart(Intent intent, int startId) {
		Bundle extras = intent.getExtras();
		int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
		if (extras != null) {
			mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);
		}

		RemoteViews updateViews = buildUpdate(this, mAppWidgetId);
		if (updateViews != null) {
			AppWidgetManager manager = AppWidgetManager.getInstance(this);
			manager.updateAppWidget(mAppWidgetId, updateViews);
		}
	}

	

	public RemoteViews buildUpdate(Context context, int appWidgetId) {

		SharedPreferences prefs = context.getSharedPreferences(
				RssFeedWidgetConfiguration.PREFS_NAME, MODE_WORLD_READABLE);

		String feedAlertType = prefs.getString(
				RssFeedWidgetConfiguration.PREF_PREFIX_KEY + appWidgetId
						+ R.id.widget_configuration_dropdown, "ALERTTYPE_NONE");
		String feedNewsSite = prefs.getString(
				RssFeedWidgetConfiguration.PREF_PREFIX_KEY + appWidgetId
						+ R.id.widget_configuration_siteselection_dropdown,
				"SITE_SKYNEWS");

		String currentFeed = prefs.getString(
				RssFeedWidgetConfiguration.PREF_PREFIX_KEY + appWidgetId
						+ CURRENT_FEED, "");

		String rssFeedUrl = "http://news.sky.com/sky-news/rss/home/rss.xml";
		String webPageUrl = "http://www.skynews.com";
		String widgetImage = SITE_SKY_NEWS;

		if (SITE_SKY_SPORTS.equalsIgnoreCase(feedNewsSite)) {
			rssFeedUrl = "http://www.skysports.com/rss/0,20514,11095,00.xml";
			webPageUrl = "http://www.skysports.com";
			widgetImage = SITE_SKY_SPORTS;
		}

		RssFeed rssFeed = invokeRssFeedService(rssFeedUrl);
		StringBuffer completeFeed = transformRssFeedToString(rssFeed);
		Log.e(RssReaderService.class.getName(), String.format(
				"[current feed is-->%s] and [new feed is--->%s]", currentFeed,
				completeFeed.toString()));

		RemoteViews updateViews = null;
		if (!currentFeed.equalsIgnoreCase(completeFeed.toString())) {

			updateViews = new RemoteViews(context.getPackageName(),
					R.layout.widget_word);

			updateViews.setTextViewText(R.id.word_title, completeFeed
					.toString());
			Intent defineIntent = new Intent(Intent.ACTION_VIEW, Uri
					.parse(webPageUrl));
			PendingIntent pendingIntent = PendingIntent.getActivity(context,
					0 /* no requestCode */, defineIntent, 0 /* no flags */);
			updateViews.setOnClickPendingIntent(R.id.word_title, pendingIntent);

			if (SITE_SKY_NEWS.equalsIgnoreCase(widgetImage)) {
				updateViews.setImageViewResource(R.id.icon,
						R.drawable.skynews_logo);
			} else if (SITE_SKY_SPORTS.equalsIgnoreCase(widgetImage)) {
				updateViews.setImageViewResource(R.id.icon,
						R.drawable.skysports_logo);
			}

			raiseNotificationAndsavePrefs(appWidgetId, prefs, feedAlertType,
					currentFeed, completeFeed);

		}

		return updateViews;

	}

	private void raiseNotificationAndsavePrefs(int appWidgetId,
			SharedPreferences prefs, String feedAlertType, String currentFeed,
			StringBuffer completeFeed) {
		if (!currentFeed.equalsIgnoreCase(completeFeed.toString())) {
			Log.d("RssReaderService", "Feed Changed!!!");
			NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			Notification notification = new Notification();
			if ("ALERTTYPE_SOUND".equalsIgnoreCase(feedAlertType)) {
				notification.defaults |= Notification.DEFAULT_SOUND;
				nm.notify(R.string.app_notification_id, notification);
			} else if ("ALERTTYPE_SOUND".equalsIgnoreCase(feedAlertType)) {
				notification.defaults |= Notification.DEFAULT_VIBRATE;
				nm.notify(R.string.app_notification_id, notification);
			}
			SharedPreferences.Editor editPrefs = prefs.edit();
			editPrefs.putString(RssFeedWidgetConfiguration.PREF_PREFIX_KEY
					+ appWidgetId + CURRENT_FEED, completeFeed.toString());
			editPrefs.commit();
		}
	}

	private StringBuffer transformRssFeedToString(RssFeed rssFeed) {
		StringBuffer completeFeed = new StringBuffer();
		for (FeedItem feedItem : rssFeed.getFeedList()) {
			String formattedString = MessageFormat.format(
					"<a href=\"{0}\">{1}</a>  ", feedItem.getLink(), feedItem
							.getTitle());
			Spanned fromHtml = Html.fromHtml(formattedString);
			completeFeed.append(fromHtml);
			completeFeed.append("   ");
		}
		return completeFeed;
	}

	private RssFeed invokeRssFeedService(String rssFeedUrl) {
		RssFeedHandler rssFeedHandler = new RssFeedHandler();
		RssFeed rssFeed = null;
		try {

			rssFeed = rssFeedHandler.createFeed(new URL(rssFeedUrl));
		} catch (MalformedURLException e) {
			Log.e(TAG, "Malformed URl Exception", e);
		} catch (Throwable e) {
			Log.e(TAG, "Some throwable exception", e);

		}
		return rssFeed;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onBind(android.content.Intent)
	 */
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

}
